package com.xgkj.diyiketang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.data.CaiPinInfo;
import com.xgkj.diyiketang.task.AddSellerShareNumTask;
import com.xgkj.diyiketang.task.CaiPinListTask;
import com.xgkj.diyiketang.task.ZanShangJiaTask;
import com.xgkj.diyiketang.util.AccessTokenKeeper;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.VideoAdapter;
import com.xgkj.diyiketang.data.SellerInfo;
import com.xgkj.diyiketang.data.VideoInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.GetSellerVideoListTask;
import com.xgkj.diyiketang.task.ShangJiaDetailTask;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.weidget.ImageCycleView;
import com.xgkj.diyiketang.weidget.MyScrollView;
import com.xgkj.diyiketang.weidget.NoScrollGridView;
import com.xgkj.diyiketang.wxapi.WXEntryActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrater on 2016/3/20.
 */
public class SellerDetailActivity extends BaseActivity implements MyScrollView.OnScrollListener, View.OnClickListener, IWeiboHandler.Response {
    private Context mContext;
    private String businessid;
    private SellerInfo sinfo;
    private MyScrollView mScrollView;
    private int sellerdetailTaskID = -1;
    private int currentPage = 1;
    private int size = 2;
    private TextView mTitle;
    private ImageView mSellerLogo;
    private TextView mSellerName;
    private RatingBar rating;
    private TextView mRenjun;
    private TextView mAddr;
    private TextView mJianjie;
    private ImageView mPhone;
    private TextView back;
    private ImageView share;
    private PopupWindow popWindow;

    private NoScrollGridView mGridView;
    private VideoAdapter mAdapter;
    private int videoListTaskId = -1;
    private int tuijiancaiTaskId = -1;
    private String share_path;

    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private String weibouserid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private String shoucangtype;
    public static Tencent mTencent;

    private String share_title;
    private TextView moreSellerVideo;
    private RelativeLayout xiangguan;
    //private LinearLayout toupiaoLayout;
    private TextView mTuijianCai;
    private String mTitleName;
    private int addShareNumTaskId = -1;
    private boolean isZan;
    private TextView zan;
    private int zanTaskID = -1;
    private LinearLayout tjcLayout;
    private ImageCycleView cycleView;
    private ArrayList<String> logos_arr = new ArrayList<String>();
    private String address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seller_detail);
        mContext = this;
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
                ProtocolConst.WEIBO_APP_KEY);//这粒要换
        mWeiboShareAPI.registerApp();
        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }
        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboShareAPI.handleWeiboResponse(intent,this);
    }


    private void initView() {
        Intent intent = getIntent();
        businessid = intent.getStringExtra("BSUINESSID");
        share_path = "http://www.chiboker.com:8096/liveshow/merchant_detail.html?businessId=" + businessid + "";
        mScrollView = (MyScrollView) findViewById(R.id.seller_scrollView);
        mScrollView.setOnScrollListener(this);
        mGridView = (NoScrollGridView) findViewById(R.id.seller_video_list);
        mAdapter = new VideoAdapter(mContext);
        mGridView.setAdapter(mAdapter);
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        back.setFocusable(true);
        back.setFocusableInTouchMode(true);
        back.requestFocus();

        mTitle = (TextView) findViewById(R.id.seller_name_title);
        mSellerLogo = (ImageView) findViewById(R.id.fooddetail_logo);
        mSellerLogo.setFocusable(true);
        mSellerLogo.setFocusableInTouchMode(true);
        mSellerLogo.requestFocus();
        mSellerName = (TextView) findViewById(R.id.sellername);
        rating = (RatingBar) findViewById(R.id.ratingbar_Small);
        mRenjun = (TextView) findViewById(R.id.sellrenjun);
        mAddr = (TextView) findViewById(R.id.seller_addr);
        mAddr.setOnClickListener(this);
        mJianjie = (TextView) findViewById(R.id.seller_jianjie);
        mPhone = (ImageView) findViewById(R.id.seller_phone);
        share = (ImageView) findViewById(R.id.seller_share);
        share.setOnClickListener(this);
        moreSellerVideo = (TextView) findViewById(R.id.more_sellervideo);
        moreSellerVideo.setOnClickListener(this);
        xiangguan = (RelativeLayout) findViewById(R.id.xiangguanshipin);
        mTuijianCai = (TextView) findViewById(R.id.tuijiancai);
        mTuijianCai.setOnClickListener(this);
        tjcLayout = (LinearLayout) findViewById(R.id.tjcLayout);
        zan = (TextView) findViewById(R.id.zan);
        zan.setOnClickListener(this);
        cycleView = (ImageCycleView) findViewById(R.id.fooddetail_logo_more);
//        toupiaoLayout = (LinearLayout) findViewById(R.id.toupiao);
//        toupiaoLayout.setOnClickListener(this);

        initPopWindow();
        getData();
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        ((ImageView) view.findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weibo))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibosdk_toast_share_success,
                        Toast.LENGTH_LONG).show();
                //doShareWeiboGetPoint();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibosdk_toast_share_canceled,
                        Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(
                        this,
                        getString(R.string.weibosdk_toast_share_failed)
                                + "Error Message: " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }
    }

    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            addShareNum();
            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);

            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)){

            }else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)){

            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }

    private void getVideoList() {
        GetSellerVideoListTask svTask = new GetSellerVideoListTask(size, currentPage, businessid);
        svTask.addListener(sellerDetailTask);
        videoListTaskId = getEatShowApp().getTaskManager().addTask(svTask);

    }

    private void getTuiJianCai() {
        CaiPinListTask cTask = new CaiPinListTask(10, currentPage, businessid);
        cTask.addListener(sellerDetailTask);
        tuijiancaiTaskId = getEatShowApp().getTaskManager().addTask(cTask);
    }

    @Override
    public void onScroll() {
        getData();
    }

    private void getData() {
        if (currentPage == 0) {
          //  Toast.makeText(mContext, R.string.no_more, Toast.LENGTH_SHORT).show();
            return;
        }
        if (sellerdetailTaskID != -1) {
            return;
        }
        ShangJiaDetailTask task = new ShangJiaDetailTask(businessid);
        task.addListener(sellerDetailTask);
        sellerdetailTaskID = getEatShowApp().getTaskManager().addTask(task);
    }

    public void addShareNum() {
        AddSellerShareNumTask adTask = new AddSellerShareNumTask(businessid);
        adTask.addListener(sellerDetailTask);
        addShareNumTaskId = getEatShowApp().getTaskManager().addTask(adTask);
    }

    private TaskEventListener sellerDetailTask = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {

            if (taskId == sellerdetailTaskID) {
                sinfo = (SellerInfo) data;
                mTitle.setText(sinfo.getBusinessName());
                mTitleName = sinfo.getBusinessName();
                share_title = mTitleName;
                String anchorImgUrl = sinfo.getBusinessLogo();
                if (anchorImgUrl != null && anchorImgUrl.length() > 0) {
                    ImageCache.getInstance(mContext).loadBitmapToView(mSellerLogo, anchorImgUrl, null);
                }
                String logos = sinfo.getBusinessImages();
                String[] logos_shuzu = logos.split(",");
                logos_arr.clear();
                for (int i = 0;i<logos_shuzu.length;i++){
                    logos_arr.add(logos_shuzu[i]);
                }
                if (logos_arr.size() == 0){
                    mSellerLogo.setVisibility(View.VISIBLE);
                    mSellerLogo.setImageResource(R.drawable.zhanweitu);
                    cycleView.setVisibility(View.GONE);
                }else {
                    mSellerLogo.setVisibility(View.GONE);
                    cycleView.setVisibility(View.VISIBLE);
                }
                cycleView.setImageResources(logos_arr, new ImageCycleView.ImageCycleViewListener() {
                    @Override
                    public void displayImage(String imageURL, ImageView imageView) {
                        if (TextUtils.isEmpty(imageURL)){
                            imageView.setImageResource(R.drawable.zhanweitu);
                        }else {
                            ImageCache.getInstance(mContext).loadBitmapToView(imageView, imageURL, ViewUtil.getImageSize(mContext,R.drawable.default_big_image));
                        }
                    }

                    @Override
                    public void onImageClick(int position, View imageView) {

                    }
                });
                isZan = sinfo.getIsZan();
                if (!isZan) {
                    zan.setClickable(false);
                    zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_checked, 0, 0);
                } else {
                    zan.setClickable(true);
                    zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_unchecked, 0, 0);
                }
                rating.setRating(Float.parseFloat(sinfo.getBusinessScore()));
                String price_per = sinfo.getAverageSpend()== null ? "0" :sinfo.getAverageSpend();
                mRenjun.setText("人均￥" + price_per);
                mAddr.setText(sinfo.getAddress());
                address = sinfo.getAddress();
                mJianjie.setText(sinfo.getIntroduction());
                mSellerName.setText(sinfo.getBusinessName());
                mPhone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), "请拨打" + sinfo.getTelephone(), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent call_intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + sinfo.getTelephone()));
                                startActivity(call_intent);
                            }
                        }, null);
                    }
                });
                getVideoList();
            } else if (taskId == videoListTaskId) {
                videoListTaskId = -1;
                if (currentPage == 1) {
                    mAdapter.clearData();

                }

                List<VideoInfo> attentionList = new ArrayList<VideoInfo>();
                if (data != null) {
                    attentionList = (List<VideoInfo>) data;
                }

                if (attentionList != null && attentionList.size() > 0) {
                    mAdapter.updateData(attentionList);
                } else {
                    xiangguan.setVisibility(View.GONE);
                }

                currentPage = result;
                getTuiJianCai();
            } else if (taskId == tuijiancaiTaskId) {
                List<CaiPinInfo> caiList = new ArrayList<CaiPinInfo>();
                if (data != null) {
                    caiList = (List<CaiPinInfo>) data;
                }

                if (caiList.size() == 0) {

                    mTuijianCai.setOnClickListener(null);

                }
                String appName = "";
                for (int i = 0; i < caiList.size(); i++) {
                    String names = caiList.get(i).getDishName();
                    appName += names + " ";

                }
                mTuijianCai.setText(appName);


            } else if (taskId == addShareNumTaskId) {
                PalLog.e("增加分享数", "成功");
            } else if (taskId == zanTaskID) {
                sinfo.setIsZan(false);
                zan.setClickable(false);
                zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_checked, 0, 0);
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == videoListTaskId) {
                videoListTaskId = -1;
            } else if (taskId == sellerdetailTaskID) {
                sellerdetailTaskID = -1;
            } else if (taskId == addShareNumTaskId) {
                addShareNumTaskId = -1;
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.seller_share:
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.share_to_timeline:
                //addShareNum();
                weixinsharetype = "sharefriends";
                shareToWeiXin(share_path, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
               // addShareNum();
                weixinsharetype = "sharefriend";
                shareToWeiXin(share_path, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
              //  addShareNum();
                shareToWeiBo(share_path);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:
              //  addShareNum();
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com:8096/liveshow/images/app_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;

            case R.id.more_sellervideo:
                Intent sIntent = new Intent(mContext, MoreVideoListActivity.class);
                sIntent.putExtra("BUSINESSID", businessid);
                sIntent.putExtra(ProtocolConst.MORE_FROM, ProtocolConst.FORM_SELLER);
                mContext.startActivity(sIntent);
                break;
            case R.id.toupiao:
                Intent tpIntent = new Intent(mContext, SellerPingLunActivity.class);
                mContext.startActivity(tpIntent);
                break;
            case R.id.tuijiancai:
                Intent tInent = new Intent(mContext, CaiPinListActivity.class);
                tInent.putExtra("TITLE", mTitleName);
                tInent.putExtra("BUSINESSID", businessid);
                tInent.putExtra("FROM",1);
                startActivity(tInent);
                break;
            case R.id.zan:
                ZanShangJiaTask zsTask = new ZanShangJiaTask(businessid);
                zsTask.addListener(sellerDetailTask);
                zanTaskID = getEatShowApp().getTaskManager().addTask(zsTask);
                break;
            case R.id.seller_addr:
                String city = EatShowSetting.getInstance(mContext).getLocal();
                Intent wInent = new Intent(mContext,MapActivity.class);
                wInent.putExtra("CITY",city);
                wInent.putExtra("ADDR", address);
                startActivity(wInent);
                break;

        }
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            addShareNum();
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };


    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mWeixinShareReceive != null){
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine){
            msg.title = share_title;
        }else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWeixinShareReceive != null){
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }
    }

    private void shareToWeiBo(String webpage) {

        if (mWeixinShareReceive != null){
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }

//		if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        // if (hasText) {
        // weiboMessage.mediaObject = getTextObj();
        // }
        // if (hasImage) {
        // weiboMessage.mediaObject = getImageObj();
        // }
        if (!TextUtils.isEmpty(webpage)) {
            TextObject textobject = new TextObject();
            textobject.text = "第一课堂";
            weiboMessage.textObject = textobject;
            WebpageObject mediaObject = new WebpageObject();
            mediaObject.identify = Utility.generateGUID();
            mediaObject.defaultText = "第一课堂";
            mediaObject.title = "第一课堂";
            mediaObject.description = share_title;
            mediaObject.actionUrl = webpage;
            if (weiboShareBitmap != null) {
                mediaObject.setThumbImage(weiboShareBitmap);
            } else {
                mediaObject.setThumbImage(BitmapFactory.decodeResource(
                        getResources(), R.drawable.app_icon));
            }
            weiboMessage.mediaObject = mediaObject;
        }
        // if (hasMusic) {
        // weiboMessage.mediaObject = getMusicObj();
        // }
        // if (hasVideo) {
        // weiboMessage.mediaObject = getVideoObj();
        // }
            /*
             * if (hasVoice) { weiboMessage.mediaObject = getVoiceObj(); }
			 */

        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
            weibouserid = accessToken.getUid();
        }
        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {


            @Override
            public void onWeiboException(WeiboException arg0) {
            }

            @Override
            public void onComplete(Bundle bundle) {
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
                weibouserid = newToken.getUid();
//                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
            }

            @Override
            public void onCancel() {
            }
        });


    }

}
